#include "../include/dir.h"

int handle_rmdir(session_t *session, MYSQL *mysql, int netfd, const char*destDir){
    char buf[1024] = {0};
    //逻辑删除需要知道目录ID等信息
    int parentID = -1;
    char lastToken[MAX_PATH_LEN] = {0};
    int ret = cut_path(session,mysql,destDir,&parentID,lastToken,buf,sizeof(buf));
    if(ret != 0){
        sendtlv(netfd, buf);
        return -1;
    }

    //检查目录是否存在
    char query[MAX_QUERY_LEN] = {0};
    sprintf(query,
            "select id from file where username = '%s' and parent_id = %d "
            "and filename = '%s' and filetype = 'd' and tomb = 0",
            session->username,parentID,lastToken);
    ret = mysql_query(mysql, query);
    MYSQL_QUERY_CHECK(ret, mysql);

    MYSQL_RES *table = mysql_store_result(mysql);
    MYSQL_STORE_RESULT_CHECK(table, mysql);
    if(mysql_num_rows(table) == 0){
        mysql_free_result(table);
        strncpy(buf, "目录不存在.", sizeof(buf)-1);
        sendtlv(netfd, buf);
        return -1;
    }

    //拿到要删目录ID 用于后续检查是否为空目录
    MYSQL_ROW row = mysql_fetch_row(table);
    int destDirID = atoi(row[0]);

    mysql_free_result(table);

    //直接将parent_id是该目录id的tomb置为1 不可行 若有嵌套目录 嵌套目录里的没改
    //检查是否为空目录->查以要删目录的ID为parent_id的
    bzero(query, sizeof(query));
    sprintf(query,
            "select id from file where username = '%s' and parent_id = %d "
            "and tomb = 0",
            session->username, destDirID);
    ret = mysql_query(mysql, query);
    MYSQL_QUERY_CHECK(ret, mysql);
    
    table = mysql_store_result(mysql);
    MYSQL_STORE_RESULT_CHECK(table,mysql);
    if(mysql_num_rows(table) > 0){
        mysql_free_result(table);
        strncpy(buf, "目录非空,无法删除.", sizeof(buf)-1);
        sendtlv(netfd, buf);
        return -1;
    }
    mysql_free_result(table);

    //进行逻辑删除
    sprintf(query,
            "update file set tomb = 1 where id = %d and username = '%s' and parent_id = %d "
            "and filename = '%s' and filetype = 'd'",
            destDirID,session->username,parentID,lastToken);
    ret = mysql_query(mysql, query);
    MYSQL_QUERY_CHECK(ret, mysql);

    strncpy(buf, "删除成功.", sizeof(buf)-1);
    sendtlv(netfd, buf);
    return 0;
}
